package com.simple.service.impl;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.simple.entity.MailBean;
import com.simple.service.SendMailService;

/**
 * 邮件发送
 * 参数useTemplate 是否使用模板
 * 没有中间件不建议使用模板，发送比较慢，简单邮件更快捷
 */
@Service
public class SendMailServiceImpl implements SendMailService{
	
	private static final Logger logger = LoggerFactory.getLogger(SendMailService.class);

	@Value("${spring.mail.username}")
	String mailSender;
	
	@Autowired
	TemplateEngine templateEngine;
	
	@Autowired
	JavaMailSender javaMailSender;

	@Override
	public void sendMail(MailBean mailBean,boolean useTemplate) {
		MimeMessage message=javaMailSender.createMimeMessage();
		try {
			MimeMessageHelper  helper=new MimeMessageHelper(message, true);//true支持多种组件
			helper.addTo(mailBean.getReceiver());//接收者
			helper.setSubject(mailBean.getSubject());//主题
			helper.setFrom(mailSender);//发送方
			if(useTemplate) {
				Context context=new Context();
				context.setVariables(mailBean.getMap());
				String emailContent=templateEngine.process("/mail", context);
				helper.setText(emailContent,true);
			}else {
				helper.setText("<a href="+mailBean.getMap().get("url")+">点击链接激活</a>",true);
			}
			javaMailSender.send(message);
			logger.info("--> 邮件发送成功至："+mailBean.getReceiver());
		} catch (MessagingException e) {
			e.printStackTrace();
			logger.info("--> 邮件发送失败"+e.getMessage());
		}
		
	}
}
